<?php
namespace App\Http\Controllers\ShopWeb;

use App\Http\Controllers\WebController;
use App\Http\Controllers\Business\ShopWeb\PublicBusiness;
use App\Http\Controllers\Business\ShopWeb\Auth\ShopWebAuth;
use App\Http\Controllers\Business\ShopWeb\OrderManagement\OrderManagement;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redis;

class IndexController extends WebController
{
    //登录页
    public function login() {
        if($this->request->has('type')) {
            $type = $this->request->get('type');
        } else {
            $type = 'password';
        }
        $data = [
            'type' => $type
        ];
        return view('shop.signin', $data);
    }
    //登录时获取验证码
    public function getCode() {
        $mobile = $this->request->get('mobile');
        $result = ShopWebAuth::getCode($mobile);
        if($result['status'] == 'failed') {
            return $this->responseError($result['message']);
        } else {
            return $this->responseSuccessMessage($result['message']);
        }
    }
    //提交登录数据
    public function submitLoginData() {
        $mobile = $this->request->get('mobile');
        $mobile = trim($mobile);
        $type = $this->request->get('type');
        $password = $this->request->get('password');
        $password = trim($password);
        $code = $this->request->get('code');
        $result = ShopWebAuth::login($mobile, $type, $password, $code);
        if($result['status'] == 'failed') {
            //return $this->responseError($result['message']);
            $data = [
                'message' => $result['message'],
                'type' => $type
            ];
            return view('shop.signin', $data);
        } else {
            $data = $result['data'];
            $shopUserId = $data['userid'];
            Auth::guard('shopweb')->loginUsingId($shopUserId);
            return redirect()->to('/shop/index');
        }
    }
    //首页
    public function index() {
        $shopUser = Auth::guard('shopweb')->user();
        $shopUserId = $shopUser->id;
        if($shopUser->password == '') {
            //设置密码页面
            $data = [
                'name' => $shopUser->name,
            ];
            return view('shop.set_up_password', $data);
        }
        if($this->request->has('shopids')) {
            $shopIdString = $this->request->get('shopids');
            $shopName = $this->request->get('shopname');
        } else {
            //先取redis，取不到再到数据库取
            $shopIdString = Redis::get('ShopWeb:ShopId:'. $shopUserId);
            $shopName = Redis::get('ShopWeb:ShopName:' . $shopUserId);
            if(!$shopIdString) {
                $shopIdString = $shopUser->shopid;
                if (stristr($shopIdString, ',')) {
                    $shopName = '全部';
                } else {
                    $shopName = PublicBusiness::getShopNameByShopId($shopIdString);
                }
            }
        }
        //设置redis
        Redis::setex('ShopWeb:ShopId:' . $shopUserId, 86400, $shopIdString);
        Redis::setex('ShopWeb:ShopName:' . $shopUserId, 86400, $shopName);
        $shopIds = explode(',', $shopIdString);
        if(count($shopIds) > 1) {
            //多门店
            $topResult = PublicBusiness::getAllShopsStatistic($shopIds);
            if($topResult['status'] == 'success') {
                $data['todayordercount'] = $topResult['data']['todayordercount'];
                $data['todayordersum'] = $topResult['data']['todayordersum'];
                $data['todaysalesmancount'] = $topResult['data']['todaysalesmancount'];
                $data['todaysalesmansum'] = $topResult['data']['todaysalesmansum'];
            } else {
                $data['todayordercount'] = '';
                $data['todayordersum'] = '';
                $data['todaysalesmancount'] = '';
                $data['todaysalesmansum'] = '';
            }
            $lists = [];
            foreach($shopIds as $shopId) {
                $shopListResult = PublicBusiness::getSingleShopStatistic($shopId);
                if($shopListResult['status'] == 'success') {
                    array_push($lists, $shopListResult['data']);
                }
            }
            $data['lists'] = $lists;
            $data['shopid'] = $shopIdString;
            return view('shop.index_more', $data);
        } else {
            //单门店
            if(!isset($shopIds[0])) {
                return view('errors.404');
            }
            $shopId = $shopIds[0];
            $result = PublicBusiness::getSingleShopStatistic($shopId);
            if($result['status'] == 'failed') {
                return view('errors.404');
            }
            $data = $result['data'];
            $data['shopid'] = $shopId;
            return view('shop.index_one', $data);
        }
    }
    //设置密码
    public function setShopUserPassword() {
        $password = $this->request->get('password');
        $confirmPassword = $this->request->get('confirmpassword');
        $shopUserId = Auth::guard('shopweb')->id();
        $result = ShopWebAuth::setPassword($shopUserId, $password, $confirmPassword);
        if($result['status'] == 'failed') {
            return $this->responseError($result['message']);
        } else {
            return $this->responseSuccessMessage($result['message']);
        }
    }

    //单个商家id绘制最近七个翻倍日的商家信息
    public function chartShopLastEventOrderCount() {
        $shopId = $this->request->get('shopid');
        $days = 7;
        $result = OrderManagement::chartLastEventOrderCount($shopId, $days);
        if($result['status'] == 'failed') {
            return $this->responseError($result['message']);
        }
        return $this->responseSuccessData($result['data']);
    }
    //获取登录帐号下的所有店铺
    public function getAllShopsByShopUserId() {
        $shopUser = Auth::guard('shopweb')->user();
        $shopUserId = $shopUser->id;
        $shopUserName = $shopUser->name;
        $result = PublicBusiness::getAllShopsByShopUserId($shopUserId);
        if($result['status'] == 'failed') {
            return $this->responseError($result['message']);
        } else {
            $lists = $result['data'];
            $selectShopId = Redis::get('ShopWeb:ShopId:'. $shopUserId);
            $selectShopName = Redis::get('ShopWeb:ShopName:'. $shopUserId);
            if(!$selectShopId) {
                $selectShopId = $shopUser->shopid;
                if (stristr($selectShopId, ',')) {
                    $selectShopName = '全部';
                } else {
                    $selectShopName = PublicBusiness::getShopNameByShopId($selectShopId);
                }
            }
            $data = [
                'shopusername' => $shopUserName,
                'selectshopid' => $selectShopId,
                'selectshopname' => $selectShopName,
                'lists' => $lists
            ];
            return $this->responseSuccessData($data);
        }
    }
    //账户资料
    public function userMessage() {
        $shopUser = Auth::guard('shopweb')->user();
        $shopUserName = $shopUser->name;
        $shopUserMobile = $shopUser->mobile;
        //$shopIds = $shopUser->shopid;
        $authJson = $shopUser->auth;
        $authArray = json_decode($authJson, true);
        $lists = [];
        foreach($authArray as $shopId => $v) {
            $result = PublicBusiness::getShopDetailByShopId($shopId);
            if(in_array('Admin', $v)) {
                $isAdmin = 1;
            } else {
                $isAdmin = 0;
            }
            if($result['status'] == 'success') {
                $list = [
                    'shopid' => $shopId,
                    'shopname' => $result['data']['name'],
                    'address' => $result['data']['address'],
                    'isadmin' => $isAdmin
                ];
                array_push($lists, $list);
            }
        }
        $data = [
            'name' => $shopUserName,
            'mobile' => $shopUserMobile,
            'lists'=> $lists
        ];
        return view('shop.user_message', $data);
    }
    //修改密码
    public function updatePassword() {
        $shopUserId = Auth::guard('shopweb')->id();
        $oldPassword = $this->request->get('oldpassword');
        $password = $this->request->get('password');
        $confirmPassword = $this->request->get('confirmpassword');
        $passwordUpdateType = $this->request->get('password_update_type');
        $code = $this->request->get('code');
        if($passwordUpdateType == 'oldpassword') {
            $result = ShopWebAuth::updatePasswordByOldPassword($shopUserId, $oldPassword, $password, $confirmPassword);
        } elseif($passwordUpdateType == 'sms') {
            $result = ShopWebAuth::updatePasswordBySms($shopUserId, $code, $password, $confirmPassword);
        } else {
            return $this->responseError('类型不对');
        }
        if($result['status'] == 'failed') {
            return $this->responseError($result['message']);
        } else {
            return $this->responseSuccessMessage($result['message']);
        }
    }
    //登出
    public function logout() {
        Auth::guard('shopweb')->logout();
        return redirect()->to('/shop/login');
    }
    //切换商家id
    public function selectShopId() {
        $shopIds = $this->request->get('shopids');
        return response()->make(redirect()->to('/shop/index?shopids=' . $shopIds ))->withCookie(cookie('shopids', $shopIds));
    }
    //收款
    public function collectMoneyQrCode() {
        $shopId = $this->request->get('shopid');
        if(!$shopId) {
            return view('errors.404');
        }
        $type = 'payment';
        $qrcode = [
            'type' => $type,
            'content' => $shopId
        ];
        $data = [
            'qrcode' => json_encode($qrcode)
        ];
        return view('shop.collectmoney.shop_qrcode', $data);
    }
}